<template>
    <div class="container">


        <!-- 基本搜索+功能按钮 -->
        <el-form ref="searchForm1" :inline="true" :model="searchForm" size="medium" label-width="">
            <el-card class="table_tool_bar_wrap" shadow="never">
                <div class="base_wrap">
                    <div class="left">
                        <el-form-item label="关键字搜索" prop="keyword">
                            <el-input placeholder="" v-model="searchForm.keyword" clearable/>
                        </el-form-item>
                        <el-button @click="handleSearch" type="primary" size="medium">搜索</el-button>
                        <el-button @click="handleReset" type="info" plain size="medium">重置</el-button>
                        <el-button type="text" size="medium" @click="searchFlag = !searchFlag">
                            高级搜索<i class="el-icon--right" :class="searchFlag?'el-icon-arrow-down':'el-icon-arrow-up'"></i>
                        </el-button>
                    </div>

                    <div class="right">
                        <el-button @click="handleAddOrUpdateVisible()" type="primary" size="medium" icon="el-icon-plus">新增</el-button>
                        <el-button @click="handleDelete()" type="danger" size="medium" icon="el-icon-delete" :disabled="selectionRows.length == 0">删除</el-button>
                    </div>
                </div>
            </el-card>
        </el-form>

        <!-- 高级搜索 -->
        <el-form ref="searchForm2" :inline="true" :model="searchForm" size="medium" label-width="120px">
            <el-collapse-transition>
                <el-card class="where_wrap" shadow="never" v-if="!searchFlag">
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="商品名称" prop="name">
                                <el-input placeholder="" v-model="searchForm.name" clearable/>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="分类" prop="cateId">
                                <CategoryCascader v-model="searchForm.cateId" ref="category" styles="width: 100%"></CategoryCascader>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="品牌" prop="brandId">
                                <BrandSelect v-model="searchForm.brandId" ref="brand" styles="width: 100%"></BrandSelect>
                            </el-form-item>
                        </el-col>
                        <!-- <el-col :span="6">
                            <el-form-item label="价格">
                                <el-input type="number" v-model="searchForm.priceMin" @input="numberic(searchForm, 'priceMin', $event)" style="width: 92px;margin-right:10px"></el-input>
                                -
                                <el-input type="number" v-model="searchForm.priceMax" @input="numberic(searchForm, 'priceMax', $event)" style="width: 92px;margin-left:10px"></el-input>
                            </el-form-item>
                        </el-col> -->
                    </el-row>
                </el-card>
            </el-collapse-transition>
        </el-form>

        <!-- 表格 -->
        <el-table
            class="mt10"
            ref="table"
            size="medium"
            height="500"
            empty-text="暂无数据"
            element-loading-text="给我一点时间"
            fit border highlight-current-row
            :stripe="stripe"
            v-loading="loading"
            :data="dataList"
            @expand-change="handleExpandChange"
            @selection-change="handleSelection">

            <el-table-column type="selection" width="55" prop="selection" v-if="isHideColumn('selection')" align="center"></el-table-column>
            <el-table-column label="商品图片" align="center" width="130">
                <template slot-scope="scope">
                    <el-image style="width: 60px; height: 60px" :src="scope.row.headImg" :preview-src-list="[scope.row.headImg]" fit="contain"></el-image>
                </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="name" align="left" width="350"/>
            <!-- <el-table-column label="类目"  min-width="150">
                <template slot-scope="scope">
                    <span>{{scope.row.categoryName}}{{scope.row.brandName ? ' | ' + scope.row.brandName : ''}}</span>
                </template>
            </el-table-column> -->
            <el-table-column label="价格" prop="price" min-width="150" align="left" show-overflow-tooltip>
                <template slot-scope="scope">
                    <span style="color: red" v-if="scope.row.specType==1 && scope.row.price">￥{{scope.row.price}}</span>
                    <span style="color: red" v-if="scope.row.specType==2">￥{{scope.row.minPrice}} ~ ￥{{scope.row.maxPrice}}</span>
                </template>
            </el-table-column>

            <el-table-column label="总库存" prop="totalStock" width="100" align="left" show-overflow-tooltip/>
            <el-table-column label="总销量" prop="totalSaleNum" width="100" align="left" show-overflow-tooltip/>
            <el-table-column label="当前总库存" prop="curTotalStock" width="100" align="left" show-overflow-tooltip/>
            <!-- <el-table-column label="分销比例" align="left" width="130">
                <template slot-scope="scope">
                    <div class="isCommission" v-if="scope.row.isCommission == 1">
                        <div>一级佣金：{{scope.row.firstRatio}}%</div>
                        <div>二级佣金：{{scope.row.secondRatio}}%</div>
                        <div>三级佣金：{{scope.row.threeRatio}}%</div>
                    </div>
                    <div v-else>-</div>
                </template>
            </el-table-column> -->
            <el-table-column label="排序" prop="sort" align="center" width="80"/>
            <!-- <el-table-column label="推荐" align="center" width="100px">
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.isRecom"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        :active-value="1"
                        :inactive-value="2"
                        @change="handleChangeIsRecom(scope.row)">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column label="精品" align="center" width="100px">
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.isBest"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        :active-value="1"
                        :inactive-value="2"
                        @change="handleChangeIsBest(scope.row)">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column label="热销" align="center" width="100px">
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.isHot"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        :active-value="1"
                        :inactive-value="2"
                        @change="handleChangeIsHot(scope.row)">
                    </el-switch>
                </template>
            </el-table-column>
            <el-table-column label="新品" align="center" width="100px">
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.isNew"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        :active-value="1"
                        :inactive-value="2"
                        @change="handleChangeIsNew(scope.row)">
                    </el-switch>
                </template>
            </el-table-column> -->
            <el-table-column label="上架/下架" align="center" width="100px">
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.status"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        :active-value="1"
                        :inactive-value="2"
                        @change="handleChangeStatus(scope.row)">
                    </el-switch>
                </template>
            </el-table-column>

            <el-table-column label="操作" prop="btn" v-if="isHideColumn('btn')" width="160px" align="left" fixed="right">
                <template slot-scope="scope">
                    <el-button @click="handleAddOrUpdateVisible(scope.row.id)" type="text" size="small">编辑</el-button>
                    <el-button @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
                    <!-- <el-button @click="handleDrawerVisible(scope.row)" type="text" size="small">详情</el-button> -->

                    <el-dropdown @command="handleCommand">
                        <span class="el-dropdown-link">
                            更多<i class="el-icon-arrow-down el-icon--right"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item :command="beforeHandleCommand(scope.$index, scope.row, 'sku')">SKU明细</el-dropdown-item>
                            <!-- <el-dropdown-item :command="beforeHandleCommand(scope.$index, scope.row, 'distribution')">分销设置</el-dropdown-item>
                            <el-dropdown-item :command="beforeHandleCommand(scope.$index, scope.row, 'seckill')">参与秒杀</el-dropdown-item>
                            <el-dropdown-item :command="beforeHandleCommand(scope.$index, scope.row, 'reduction')">满减设置</el-dropdown-item>
                            <el-dropdown-item :command="beforeHandleCommand(scope.$index, scope.row, 'discount')">折扣设置</el-dropdown-item>
                            <el-dropdown-item :command="beforeHandleCommand(scope.$index, scope.row, 'memberPrice')">会员价格</el-dropdown-item>
                            <el-dropdown-item :command="beforeHandleCommand(scope.$index, scope.row, 'stock')">库存管理</el-dropdown-item>
                            <el-dropdown-item :command="beforeHandleCommand(scope.$index, scope.row, 'coupon')">优惠劵</el-dropdown-item> -->
                        </el-dropdown-menu>
                    </el-dropdown>
                </template>
            </el-table-column>

            <!-- 展开sku信息 -->
            <!-- <el-table-column type="expand" fixed="right">
                <template slot-scope="scope">
                    <el-table :data="scope.row.skus" fit border>

                        <el-table-column label="规格图片" align="center" width="130">
                            <template slot-scope="scope">
                                <el-image style="width: 100px; height: 100px" :src="scope.row.skuImg" fit="contain"></el-image>
                            </template>
                        </el-table-column>
                        <el-table-column label="SKU名称" prop="skuName" width="200"/>
                        <el-table-column label="销售价(元)" prop="salePrice"/>
                        <el-table-column label="成本价(元)" prop="costPrice"/>
                        <el-table-column label="市场价(元)" prop="marketPrice"/>
                        <el-table-column label="库存" prop="stockNum"/>
                        <el-table-column label="条码" prop="barcode"/>

                    </el-table>
                </template>
            </el-table-column> -->

        </el-table>

        <!-- 分页 -->
        <TablePagination
            v-if="!searchForm.queryStockWarn"
            :total.sync="total"
            :page.sync="searchForm.page"
            :limit.sync="searchForm.limit"
            @handleSizeChange="handleSizeChange"
            @handleCurrentChange="handleCurrentChange"/>

        <!-- 弹窗, 新增 / 修改 -->
        <AddOrUpdate ref="addOrUpdate" v-on:refreshDataList="getDataList" v-on:getGoodsCount="getGoodsCount"></AddOrUpdate>

        <!-- SKU 列表 -->
        <Skus ref="skus" />

        <!-- 右侧抽屉,详情信息 -->
        <!-- <el-drawer
            class="drawer_wrap"
            size="800px"
            :visible.sync="drawerVisible"
            :with-header="false"
            :modal="true"
            direction="rtl"
            :before-close="handleCloseDrawerDetail">
            <div class="header_title">商品详情</div>

            <div class="header_body">
                <el-form :model="detail" :inline="true" label-width="120">
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="商品名称：">
                                {{detail.title}}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="类别：">
                                {{detail.categoryName}}{{detail.brandName ? ' | ' + detail.brandName : ''}}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="价格：">
                                {{detail.price}}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="库存：">
                                {{detail.totalStock}}
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </el-drawer> -->

    </div>
</template>

<script>
import CategoryCascader from "@/views/mall/pmscategory/components/category-cascader";
import BrandSelect from "@/views/mall/pmsbrand/components/brand-select";
import TableMixin from '@/mixin/TableMixin'
import TableTools from '@/views/components/table/table-tools'
import TablePagination from '@/views/components/table/table-pagination'
import AddOrUpdate from './add-or-update-dialog'
import Skus from './skus'
import SingleUpload from '@/views/components/upload/single-upload'
export default {
    mixins: [TableMixin],
    components: {
        TableTools,
        TablePagination,
        AddOrUpdate,
        SingleUpload,
        CategoryCascader,
        BrandSelect,
        Skus
    },

    data() {
        return {
            dataList: [],
            total: 0,
            loading: false,
            drawerVisible: false,
            selectionRows: [],
            searchFlag: true,
            searchForm: {
                page: 1,
                limit: 10,
                sortColumns: 'sort,ctime',
                sortType: 'desc',
                keyword: null,
                cateId: null,
                brandId: null,
                name: null,
                status: null,
                isRecom: null,
                queryStockWarn: null,
                priceMin: null,
                priceMax: null,
                ctime: null,
                utime: null
            },
            detail: {
                id: null,
                cateId: null,
                brandId: null,
                name: null,
                status: null,
                ctime: null,
                utime: null
            },

            catePathSub: null,
            brandIdSub: null,

            inputVisible: [],
            inputValue: [],
        }
    },

    props: {
        params: {
            type: Object
        }
    },

    created() {
        // tabs 组件传入的参数
        let {status, queryStockWarn} = this.params

        if(undefined != status) {
            // 查询上架或仓库中的商品
            this.searchForm.status = status
        } else if(queryStockWarn) {
            // 查询库存预警商品
            this.searchForm.queryStockWarn = queryStockWarn
        }
    },

    mounted() {
        this.$nextTick(() => {
            this.catePathSub = PubSub.subscribe("catePathId", (msg, val) => {
                this.searchForm.cateId = val[val.length-1];
            });
            this.brandIdSub = PubSub.subscribe("brandId", (msg, val) => {
                this.searchForm.brandId = val;
            });

            this.getDataList()
        })
    },

    methods: {

        /**
         * 侧边栏抽屉打开
         */
        handleDrawerVisible(row) {
            this.detail = row
            this.drawerVisible = true
        },

        /**
         * 新增或编辑
         */
        handleAddOrUpdateVisible(id) {
            // 表单页面
            // if(!id) {
            //     this.$router.push({name: 'goods_form'})
            // } else {
            //     this.$router.push({name: 'goods_form', query: {id: id}})
            // }

            // 表单窗口
            this.$nextTick(() => {
                this.$refs.addOrUpdate.init(id)
            })
        },

        /**
         * sku表格
         */
        handleSkusVisible(id) {
            this.$refs.skus.init(id)
        },

        /**
         * 删除
         */
        async handleDelete(row) {
            let ids = []
            if (row) {
                ids.push(row.id)
            }
            if(this.selectionRows) {
                this.selectionRows.filter((item, index) => {
                    ids.push(item.id)
                })
            }
            if (ids.length <= 0) {
                this.$notify({ title: '提示', message: '请选择需要删除的记录！', type: 'info' });
            } else {
                const confirm = await this.$confirm('确定要删除？', '提示', { type: 'warning' }).catch(() => {})
                if(confirm) {
                    const res = await this.$http({
                        url: '/mall/pmsspu/delete',
                        method: 'POST',
                        data: ids
                    })
                    if (this.ResultMessage(res)) {
                        this.getDataList()
                    }
                }
            }
        },

        /**
         * 获取表格数据
         */
        async getDataList(flag) {
            if(flag) {
                // 关闭窗口是清空cateId和brandId
                this.searchForm.cateId = null
                this.searchForm.brandId = null
            }

            this.loading = true
            const res = await this.$http({
                url: '/mall/pmsspu/page',
                method: 'GET',
                params: this.searchForm
            })
            if (this.ResultMessage(res, false)) {
                this.dataList = res.data.records || []
                this.total = res.data.total

                this.dataList.forEach(item => {
                    this.inputVisible.push({ view: false });
                    this.inputValue.push({ val: item.sort });
                })
            }
            this.loading = false
        },

        /**
         * 把每一行的索引放进row
         */
        tableRowClassName ({row, rowIndex}) {
            row.index = rowIndex;
        },

        /**
         * 推荐
         */
        async handleChangeIsRecom(row) {
            this.loading = true
            await this.$http({
                url: '/mall/pmsspu/changeIsRecom/'+row.id+'/'+row.isRecom,
                method: 'GET'
            })
            this.loading = false
        },
        /**
         * 精品
         */
        async handleChangeIsBest(row) {
            this.loading = true
            await this.$http({
                url: '/mall/pmsspu/changeIsBest/'+row.id+'/'+row.isBest,
                method: 'GET'
            })
            this.loading = false
        },
        /**
         * 热销
         */
        async handleChangeIsHot(row) {
            this.loading = true
            await this.$http({
                url: '/mall/pmsspu/changeIsHot/'+row.id+'/'+row.isHot,
                method: 'GET'
            })
            this.loading = false
        },
        /**
         * 新品
         */
        async handleChangeIsNew(row) {
            this.loading = true
            await this.$http({
                url: '/mall/pmsspu/changeIsNew/'+row.id+'/'+row.isNew,
                method: 'GET'
            })
            this.loading = false
        },

        /**
         * 上架/下架
         */
        async handleChangeStatus(row) {
            this.loading = true
            await this.$http({
                url: '/mall/pmsspu/changeStatus/'+row.id+'/'+row.status,
                method: 'GET'
            })
            this.loading = false

            this.getDataList()

            this.getGoodsCount()
        },

        /**
         * 调用父组件方法，刷新商品数量
         */
        getGoodsCount() {
            this.$emit('getGoodsCount')
        },

        /**
         * 展开商品sku信息
         */
        handleExpandChange(row, expanded) {
            console.log(row);
            console.log(expanded);
        },

        /**
         * el-dropdown 传入多参数
         */
        beforeHandleCommand(index, row, name){
            return { 'index': index, 'row': row, 'name': name }
        },
        /**
         * el-dropdown 更多操作
         */
        async handleCommand(command) {
            const { name, row } = command
            if (name === 'sku') {
                // 商品sku信息
                this.handleSkusVisible(row.id)
            } else if (name === '') {

            } else if(name === '') {

            }
        },

        /**
         * 搜索
         */
        handleSearch() {
            this.getDataList()
        },
        /**
         * 重新加载数据表格
         */
        handleReload() {
            this.getDataList()
        },
        /**
         * 重置搜索表单
         */
        handleReset() {
            this.searchForm.priceMin = null
            this.searchForm.priceMax = null
            this.searchForm.cateId = null
            this.$refs.category.paths = []
            this.$refs.brand.brandId = null
            this.$refs.searchForm1.resetFields()
            this.$refs.searchForm2.resetFields()

            this.getDataList()
        }

    }

}
</script>

<style lang="scss" scoped>
.el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
    font-size: 12px;
    margin-left: 10px;
}
.el-icon-arrow-down {
    font-size: 12px;
}

.isCommission{
    display: flex;
    flex-direction: column;
}

</style>
